﻿using System;
using System.Collections.Generic;
using System.Linq;
using Hammock;
using Newtonsoft.Json.Linq;
using RedBit.UserVoice.Model;

namespace RedBit.UserVoice.Services
{
    public class UVForumService : BaseUVApi
    {
        #region Get Forums
        public static void GetForums(Action<ICollection<UVForum>> handler)
        {
            var client = new RestClient
            {
                Authority = string.Format(UserVoiceConstants.URL_TEMPLATE, UserVoiceAPI.AppName),
            };

            var request = new RestRequest
            {
                Path = UserVoiceConstants.GET_FORUMS_SUFFIX
            };

            request.AddParameter("client", UserVoiceAPI.Key);

            client.BeginRequest(request, HandleGetForumsResponse, handler);
        }

        private static void HandleGetForumsResponse(RestRequest rq, RestResponse rs, object token)
        {
            var response = JObject.Parse(rs.Content);
            var jsonObjects = response["forums"] as JArray;

            var forums =
                from obj in jsonObjects
                select new UVForum
                {
                    Id = obj["id"].Value<string>(),
                    Name = obj["name"].Value<string>(),
                };

            var handler = token as Action<ICollection<UVForum>>;

            handler(forums.ToList());
        }
        #endregion Get Suggestions for Forum
    }
}
